package com.example.demo.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class FileUploadController {

    private static final String UPLOAD_DIR = "/opt/cao/download";

    @PostMapping("/upload")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 确保目录存在
            File directory = new File(UPLOAD_DIR);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 保存文件
            String fileName = file.getOriginalFilename();
            Path filePath = Paths.get(UPLOAD_DIR, fileName);
            Files.copy(file.getInputStream(), filePath);

            return ResponseEntity.ok().body("文件上传成功: " + fileName);
        } catch (IOException e) {
            return ResponseEntity.badRequest().body("文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/files")
    public ResponseEntity<?> getFileList() {
        try {
            File directory = new File(UPLOAD_DIR);
            if (!directory.exists()) {
                directory.mkdirs();
                return ResponseEntity.ok(new ArrayList<>());
            }

            List<FileInfo> fileInfos = Arrays.stream(directory.listFiles())
                    .filter(File::isFile)
                    .map(file -> new FileInfo(
                            file.getName(),
                            file.length(),
                            file.lastModified()
                    ))
                    .sorted(Comparator.comparing(FileInfo::getUploadTime).reversed())
                    .collect(Collectors.toList());

            return ResponseEntity.ok(fileInfos);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取文件列表失败: " + e.getMessage());
        }
    }
    
    // 获取最新上传的文件信息
    @GetMapping("/files/latest")
    public ResponseEntity<?> getLatestFile() {
        try {
            File directory = new File(UPLOAD_DIR);
            if (!directory.exists() || directory.listFiles() == null || directory.listFiles().length == 0) {
                return ResponseEntity.ok().body(null);
            }

            File latestFile = Arrays.stream(directory.listFiles())
                    .filter(File::isFile)
                    .max(Comparator.comparing(File::lastModified))
                    .orElse(null);

            if (latestFile == null) {
                return ResponseEntity.ok().body(null);
            }

            FileInfo fileInfo = new FileInfo(
                    latestFile.getName(),
                    latestFile.length(),
                    latestFile.lastModified()
            );

            return ResponseEntity.ok().body(fileInfo);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取最新文件失败: " + e.getMessage());
        }
    }

    // 文件下载接口
    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        try {
            Path filePath = Paths.get(UPLOAD_DIR).resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            
            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }

            // 尝试确定文件的内容类型
            String contentType = null;
            try {
                contentType = Files.probeContentType(filePath);
            } catch (IOException e) {
                // 忽略错误，使用默认类型
            }
            
            // 如果无法确定内容类型，则使用通用二进制流类型
            if (contentType == null) {
                contentType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType(contentType))
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } catch (MalformedURLException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    // 文件信息类
    static class FileInfo {
        private String name;
        private long size;
        private long uploadTime;

        public FileInfo(String name, long size, long uploadTime) {
            this.name = name;
            this.size = size;
            this.uploadTime = uploadTime;
        }

        public String getName() {
            return name;
        }

        public long getSize() {
            return size;
        }

        public long getUploadTime() {
            return uploadTime;
        }
    }
}